//消息页
'use strict';
import React, { Component } from 'react';
import {
  View,
  ListView,
  Text,
  StyleSheet,
  ActivityIndicator,
} from 'react-native';
import NavBar from '../components/NavigatorBar';
import { Actions } from 'react-native-router-flux';
import * as defaultStyles from '../constants/DefaultStyles';
import PullToRefreshListView from 'react-native-smart-pull-to-refresh-listview';


export default class MessagesContainer extends Component {
  constructor(props) {
    super(props);
    this.state = {
      messages: [],
    }
  }

  componentDidMount() {
    this._pullToRefreshListView.beginRefresh();
  }

  _update() {
    storage.load({
      key: merid,
      autoSync: true,
      syncInBackground: true,
    }).then(ret => {
      this._pullToRefreshListView.endRefresh();
      console.log(ret);
      let arr = [];
      if (ret.messages === undefined) {
        this.setState({messages: []});
      }
      else {
        this.setState({messages: ret.messages})
      }
    }).catch(err => {
      console.warn(err.message);
      this._pullToRefreshListView.endRefresh();
      this.setState({messages: []});
      switch (err.name) {
        case 'NotFoundError':
          break;
        case 'ExpiredError':
          break;
      }
    });
  }

  _renderRow(rowData) {
    return (
      <View style={{height: 60, alignItems: 'center', paddingLeft: 20,
      borderBottomWidth: 0.8, borderBottomColor: '#F4F4F4', flexDirection: 'row',
      paddingRight: 20}}>
        <Text style={{fontSize: 17, flex: 3}}>{rowData['alertContent']}</Text>
        <Text style={{fontSize: 13, flex: 1, textAlign: 'right'}}>{rowData['time']}</Text>
      </View>
    );
  }

  _cleanMessages() {
    storage.remove({
      key: merid
    }).then(this._pullToRefreshListView.beginRefresh());
  }

  render() {
    let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
      return (
        <View style={{flex: 1}}>
          <NavBar leftImage="angle-left" leftClick={() => Actions.pop()} title="消息"
                  navBarColor={defaultStyles.LIGHTBLUE}
                  rightText={this.state.messages.length === 0 ? undefined : '全部清除'}
                  rightClick={() => this._cleanMessages()}/>
          <View style={{position: 'absolute', left: 0, right: 0, top: 64, bottom: 0,
          justifyContent: 'center', alignItems: 'center'}}>
            <Text style={{fontSize: 20}}>暂无消息</Text>
          </View>
          <View style={{flex: 1}}>
            <PullToRefreshListView
              ref={ (component) => this._pullToRefreshListView = component }
              viewType={PullToRefreshListView.constants.viewType.listView}
              dataSource={ds.cloneWithRows(this.state.messages.reverse())}
              renderRow={this._renderRow.bind(this)}
              style={{flex: 1}}
              enableEmptySections={true}
              renderHeader={this._renderHeader}
              contentContainerStyle={{backgroundColor: this.state.messages.length === 0 ? 'rgba(0,0,0,0)' : 'white', borderWidth: 0}}
              //renderFooter={this._renderFooter}
              //renderSeparator={(sectionID, rowID) => <View style={styles.separator} />}
              onRefresh={() => this._update()}
              pullDownDistance={35}
              pullDownStayDistance={50}
              enabledPullUp={false}
            />
          </View>
        </View>
      );
  }
  _renderHeader = (viewState) => {
    let {pullState, pullDistancePercent} = viewState
    let {refresh_none, refresh_idle, will_refresh, refreshing,} = PullToRefreshListView.constants.viewState
    pullDistancePercent = Math.round(pullDistancePercent * 100)
    switch(pullState) {
      case refresh_none:
        return (
          <View style={{height: 50, justifyContent: 'center', alignItems: 'center', backgroundColor: defaultStyles.WHITEOFBACKGROUND,}}>
            <Text></Text>
          </View>
        )
      case refresh_idle:
        return (
          <View style={{height: 50, justifyContent: 'center', alignItems: 'center', backgroundColor: defaultStyles.WHITEOFBACKGROUND,}}>
            <Text>下拉刷新数据{pullDistancePercent}%</Text>
          </View>
        )
      case will_refresh:
        return (
          <View style={{height: 50, justifyContent: 'center', alignItems: 'center', backgroundColor: defaultStyles.WHITEOFBACKGROUND,}}>
            <Text>松手刷新数据{pullDistancePercent > 100 ? 100 : pullDistancePercent}%</Text>
          </View>
        )
      case refreshing:
        return (
          <View style={{flexDirection: 'row', height: 50, justifyContent: 'center', alignItems: 'center', backgroundColor: defaultStyles.WHITEOFBACKGROUND,}}>
            {this._renderActivityIndicator()}<Text>数据请求中</Text>
          </View>
        )
    }
  }

  _renderActivityIndicator() {
    return ActivityIndicator ? (
        <ActivityIndicator
          style={{marginRight: 10,}}
          animating={true}
          color={'gray'}
          size={'small'}/>
      ) : Platform.OS == 'android' ?
        (
          <ProgressBarAndroid
            style={{marginRight: 10,}}
            color={'gray'}
            styleAttr={'Small'}/>

        ) :  (
          <ActivityIndicatorIOS
            style={{marginRight: 10,}}
            animating={true}
            color={'gray'}
            size={'small'}/>
        )
  }
}

const styles = StyleSheet.create({

})